﻿#include <QUrl>
#include <QFile>
#include <QDir>

#ifdef Q_OS_WIN
#include <QProcess>
#else
#include <QDesktopServices>
#endif

#include "FileSystemHandler.h"

namespace Domy {

FileSystemHandler::FileSystemHandler(QObject *parent)
    : QObject(parent)
{

}

FileSystemHandler::~FileSystemHandler()
{

}

void FileSystemHandler::showInExplorer(const QString &file_path)
{
#ifdef Q_OS_WIN
        QString f = QString("explorer.exe /select,\"%1\"")
                .arg(QUrl::fromLocalFile(file_path).toString());
        QProcess::startDetached(f);
#else
        QDesktopServices::openUrl(QUrl::fromLocalFile(QFileInfo(file_path).dir().path()));
#endif

}

bool FileSystemHandler::rename(const QFileInfo &old_file, const QString &new_name, QFileInfo &new_file)
{
    if (old_file.fileName() == new_name) {
        new_file = old_file;
        return true;
    }

    QString file_dir = old_file.dir().path();

    QString new_file_path = file_dir + "/" + new_name;

    bool rslt = QFile::rename(old_file.absoluteFilePath(), new_file_path);
    if (rslt) {
        new_file = QFileInfo(new_file_path);
    }
    return rslt;
}

bool FileSystemHandler::createFile(const QString &file_path)
{
    bool rslt = false;
    QFileInfo fi(file_path);
    if (!fi.exists() && FileSystemHandler::checkName(fi.fileName())) {
        QFile file(file_path);
        if (file.open(QIODevice::WriteOnly)) {
            rslt = true;
            file.close();
        }
    }
    return rslt;
}

bool FileSystemHandler::createDir(const QString &dir_path)
{
    bool rslt = false;
    QDir dir(dir_path);
    if (FileSystemHandler::checkName(dir.dirName())) {
        rslt = dir.mkpath(dir_path);
    }
    return rslt;
}

bool FileSystemHandler::removeFile(const QString &path)
{
    return QFile::remove(path);
}

bool FileSystemHandler::removeDir(const QString &path)
{
    QDir dir(path);
    return dir.removeRecursively();
}

bool FileSystemHandler::checkName(const QString &name)
{
    int match = name.indexOf(QRegExp("[\\\\/:|*?\"<>]|[cC][oO][mM][1-9]|[lL][pP][tT][1-9]|[cC][oO][nM]|[pP][rR][nN]|[aA][uU][xX]|[nN][uU][lL]"));
    return (!name.isEmpty() && match < 0);
}

} // namespace Domy
